﻿using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Xml;
using System.Text.RegularExpressions;

namespace SimpleRedisClinet
{
    /// <summary>
    /// simple redis client class
    /// yangmeng(hvbird@gmail.com)
    /// 2011-01-20
    /// </summary>
    public class Redis : RedisBase
    {
        public Redis(string hostip, int port)
            : base(hostip,port)
        {
            
        }

        public static void Init(LogInterface log)
        {
            SocketPool.Init();
            SocketPool.Log = log;
        }

        /// <summary>
        /// set item
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Set<T>(string key, T obj)
        {
            return Set(key, obj, false);
        }

        /// <summary>
        /// set item
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="preserve">default is false, the value is overwrite if key exists</param>
        /// <returns></returns>
        public bool Set<T>(string key, T obj, bool preserve)
        {
            check_key(key);

            System.Text.StringBuilder sb = new StringBuilder();
            if (preserve)
                sb.Append("SETNX ");
            else
                sb.Append("SET ");

            sb.Append(key);
            sb.Append(" ");
            string strvalue = get_serializer_str<T>(obj);
            sb.Append(System.Text.Encoding.UTF8.GetByteCount(strvalue));
            sb.Append("\r\n");
            sb.Append(strvalue);
            sb.Append("\r\n");


            ResponseClass ret = send_and_receive(sb.ToString());

            if (ret.Number > 0)
                return true;

            return false;
        }

        

        /// <summary>
        /// get item
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            string cmdstr = "GET " + key + "\r\n";

            ResponseClass ret = send_and_receive(cmdstr);

            if (ret.Strings.Count > 0)
            {
                T retobj = get_deserialized_obj<T>(ret.Strings[0]);
                return retobj;
            }

            return default(T);
        }

        
    }
}
